package com.ymt.bpm.engine.handler.activity;

import com.ymt.bpm.dao.MDao;
import com.ymt.bpm.dao.Mapper;
import com.ymt.bpm.engine.handler.ActivityEventHandler;
import com.ymt.bpm.model.PActivity;
import com.ymt.bpm.util.Const;
import com.ymt.bpm.util.DateUtil;
import org.activiti.engine.delegate.event.ActivitiActivityEvent;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by Johnny on 2016/12/24.
 */
@Component
public class UserTaskHandler implements ActivityEventHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MDao dao;

    @Override
    public void onActivityStarted(ActivitiActivityEvent aae) {
        if (log.isDebugEnabled()) {
            log.debug("onActivityStarted activityId="+aae.getActivityId());
            log.debug("onActivityStarted activityName="+aae.getActivityName());
            log.debug("onActivityStarted executionId="+aae.getExecutionId());
            log.debug("onActivityStarted variables="+aae.getEngineServices().getRuntimeService().getVariables(aae.getExecutionId()));
        }
        String tenantId = aae.getEngineServices().getRuntimeService().getVariable(aae.getExecutionId(), Const.TENANT_ID, String.class);
        PActivity activity = new PActivity();
        if (tenantId!=null && tenantId.length()>0 && StringUtils.isNumeric(tenantId)) {
            activity.setTenantId(Integer.parseInt(tenantId));
        }
        activity.setPiEid(aae.getProcessInstanceId());
        activity.setActivityName(aae.getActivityName());
        activity.setActivityId(aae.getActivityId());
        activity.setType(PActivity.TYPE_USERTASK);
        activity.setCreateTime(DateUtil.getGMTDate());
        dao.insert(Mapper.PActivityMapper, "insertSelective", activity);
    }

    @Override
    public void onActivityComplete(ActivitiActivityEvent aae) {
        if (log.isDebugEnabled()) {
            log.debug("onActivityComplete activityId="+aae.getActivityId());
            log.debug("onActivityComplete activityName="+aae.getActivityName());
            log.debug("onActivityComplete executionId="+aae.getExecutionId());
            log.debug("onActivityComplete variables="+aae.getEngineServices().getRuntimeService().getVariables(aae.getExecutionId()));
        }
        String tenantId = aae.getEngineServices().getRuntimeService().getVariable(aae.getExecutionId(), Const.TENANT_ID, String.class);
        PActivity activity = new PActivity();
        if (tenantId!=null && tenantId.length()>0 && StringUtils.isNumeric(tenantId)) {
            activity.setTenantId(Integer.parseInt(tenantId));
        }
        activity.setPiEid(aae.getProcessInstanceId());
        activity.setActivityId(aae.getActivityId());
        dao.delete(Mapper.PActivityMapper, "deleteByObj", activity);
    }

}
